setLocalStorage('city', defaultCity);

/*
   * 定位
   * 先浏览器定位，后采用IP定位
   * */
function geolocation() {
    // AMap.plugin('AMap.Geolocation', function() {
    var geolocation = new AMap.Geolocation({
        // 是否使用高精度定位，默认：true
        enableHighAccuracy: true,
        // 设置定位超时时间，默认：无穷大
        timeout: 10000,
        // 定位按钮的停靠位置的偏移量，默认：Pixel(10, 20)
        buttonOffset: new AMap.Pixel(10, 20),
        //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
        zoomToAccuracy: true,
        //  定位按钮的排放位置,  RB表示右下
        buttonPosition: 'RB'
    })

    geolocation.getCurrentPosition()
    AMap.event.addListener(geolocation, 'complete', onComplete)
    AMap.event.addListener(geolocation, 'error', onError)

    // })
}

geolocation()

//解析定位结果
function onComplete(data) {
    var province = data.addressComponent.province; // 省
    var city = data.addressComponent.city; // 市
    var district = data.addressComponent.district; // 区
    var township = data.addressComponent.township; // 街道
    var name = data.formattedAddress//data.addressComponent.township + data.addressComponent.street + data.addressComponent.streetNumber,
    city = data.addressComponent.city
    name = name.replace(province, '').replace(city, '').replace(district, '');
    if (data.addressComponent.building) {
        name = data.addressComponent.building;
    } else if (name.length > 9) {
        name = name.replace(township, '');
    }
    // var option = "<option value='' selected>"+name+"</option>";
    // $('#qidian_input').html(option);
    //setLocalStorage('city', city == null ? "厦门市" : city);
    var startLocation = null;
    if (data != undefined && data.position != undefined) {// 用户通过定位已经获取了位置信息
        startLocation = {
            adcode: data.addressComponent.adcode,
            address: data.addressComponent.street + data.addressComponent.streetNumber,
            district: data.addressComponent.province + data.addressComponent.city + data.addressComponent.district,
            location: data.position,
            name: name,
            typecode: data.addressComponent.adcode
        }
        var $qidian = $('#qidian_input');
        if (!$qidian.data().name) {
            defaultCity = city;
            setLocalStorage('city', city);
            setLocalStorage(START_LOCATION_INFO, startLocation);
            $qidian.html(startLocation.name);
            $qidian.data({
                name: startLocation.name
            })
        }
        window.$location = data.position
    }


}

//解析定位错误信息
function onError(data) {
    console.log(data)
    console.log("定位失败");
}

function citySearch() {
    var citysearch = new AMap.CitySearch();
    //自动获取用户IP，返回当前城市
    citysearch.getLocalCity(function (status, result) {
        if (status === 'complete' && result.info === 'OK') {
            adcode = result.adcode;
        } else {

        }
    });
}